<template>
  <div class="save-as-template">
    <div class="save"><a-button @click="handleShowSave" type="primary">保存为模板</a-button></div>
    <a-modal v-model="visible" :title="false" @ok="handleOk" okText="确定" cancelText="取消">
      <div class="save-as-template-form">
        <CommonForm ref="formRef" :onChange="handleChange" :formData="formData" :formJson="formJson" />
      </div>
    </a-modal>

  </div>
</template>

<script >
import { mapState } from 'vuex'
import CommonForm from "@/components/CommonForm"
import { uploadImg } from "../../../../lib/upload"
import { message } from "ant-design-vue"
import { addTemplate } from "@/api/dashboard/board"

export default {
  data () {
    return {
      formData: {
        name: '',
        legend: ''
      },
      formJson: [
        {
          type: "input",
          label: "名称",
          fieldName: "name",
          initialValue: "",
          extraConfig: {
            className: "row",
          },
          rules: { required: true, message: '名称不能为空', trigger: 'blur' }
        },
        // {
        //   type: "upload",
        //   label: "图例",
        //   fieldName: "legend",
        //   initialValue: "",
        //   extraConfig: {
        //     className: "row",
        //     showUploadList: false
        //   },
        //   beforeUpload: this.beforeUpload,
        //   rules: { required: true, message: 'legend不能为空', trigger: 'blur' }
        // },
      ],
      visible: false
    }
  },
  computed: {
    ...mapState("lowCode", {
      pageSetting: state => state.pageSetting
    }),
  },
  components: {
    CommonForm
  },
  methods: {
    handleShowSave () {
      this.visible = true
    },
    handleOk () {
      this.$refs["formRef"].$refs["formRef"].validate()
      .then(values => {
        const {
          pageSetting
        } = this.$store.state.lowCode
        addTemplate({
          ...this.formData,
          style: JSON.stringify(pageSetting)
        })
        .then(data => {
          if (data.code === '000000') {
            message.success("保存成功")
            this.visible = false
          } else {
            message.error(data.message)
          }
        })
      })
    },
    handleChange (fieldName, value) {
      console.log(fieldName, value)
      this.formData[fieldName] = value
    },
    beforeUpload (file) {
      uploadImg(file, 'legend', this.formData)
      .then((img) => {
        this.formData.legend = img
        this.$forceUpdate()
        console.log(this.formData)
      })
      return false
    },
  }
}
</script>

<style lang="less" scoped>
  @import url("./index.less");
</style>
